import React, { useState, useEffect } from 'react'
import { Button, Card, Table, Space, Modal, Form, Input, Select, message } from "antd"
import { findAllCategoryApi,addCategoryApi } from "../../../apis/categoryApi"

const { Option } = Select;


const layout = {
  labelCol: {
    span: 4,
  },
  wrapperCol: {
    span: 16,
  },
};
const tailLayout = {
  wrapperCol: {
    offset: 4,
    span: 16,
  },
};

export default function ProductCategory() {
  const [dataSource, setDataSource] = useState([])
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [parentId, setParentId] = useState(0)
  const [visible, setVisible] = useState(false)
  const [categoryList,setCategoryList] = useState([])

  useEffect(() => {
    fetchData()
  }, [parentId])

  const fetchData = async () => {
    const res = await findAllCategoryApi({ parentId })
    console.log(res);
    setDataSource(res.data.data.data)
  }
  const fetchData2 = async () => {
    const res = await findAllCategoryApi({ parentId:0 })
    setCategoryList(res.data.data.data)
  }
  /**
   * 查看子分类
   */
  const findSubsCategory = (p1, p2) => {
    setParentId(p1._id)
  }
  const pageChangeEvent = (event) => {
    console.log(event);
  }
  /**
   * 点击添加按钮 弹框
   */
  const addCategory = () => {
    setIsModalOpen(true)
  }
  /**
   * 控制模态框的关闭
   */
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  /**
   * 表单区域需要用函数
   * @param {*} values 
   */
  const onFinish =async (values) => {
    values.parentId = values.parentId?values.parentId:0
    console.log(values);
    const res = await addCategoryApi(values)
    if(res.data.code){
      message.success("添加成功")
    }else{
      message.error("添加失败")
    }
  };
  const onFinishFailed = (error) => {
    console.log(error);
  }
  const typeChangeEvent = (value) => {
    if (value == "一级分类" || value == "") {
      setVisible(false)
    } else if (value == "二级分类") {
      setVisible(true)
      if(categoryList.length == 0){
        fetchData2()
      }
    }
  }
  // 表头的数据
  const columns = [
    {
      title: '编号',
      dataIndex: '_id',
    },
    {
      title: '分类名字',
      dataIndex: 'name',
    },
    {
      title: '分类类别',
      dataIndex: 'type'
    },
    {
      title: '操作',
      render: (p1, p2) => {
        return (
          <Space size="middle">
            {parentId == 0 ? <Button onClick={() => findSubsCategory(p1, p2)} type='default'>查看子分类</Button> : null}
            <Button type='primary'>删除</Button>
          </Space>
        )
      }
    },
  ];


  return (
    <Card
      title={parentId == 0 ? "商品分类" : <Button onClick={() => setParentId(0)}>返回</Button>}
      extra={<Button onClick={addCategory} type='primary'>添加</Button>}
      style={{
        width: "100%",
      }}
      loading={false}
    >
      <Table
        dataSource={dataSource}
        columns={columns}
        rowKey="_id"
        bordered={true}
        loading={false}
        pagination={{ defaultCurrent: 1, defaultPageSize: 6, showSizeChanger: true, pageSizeOptions: [3, 6, 9], showQuickJumper: true }}

      />
      {/* <Pagination onChange={pageChangeEvent} defaultCurrent={1} total={50} /> */}
      <Modal
        title="添加分类"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}>
        <Form
          {...layout}
          name="control-hooks"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          style={{
            maxWidth: 600,
          }}
        >
          <Form.Item
            name="name"
            label="分类名字"
            rules={[
              { required: true, message: "不允许为空" },
              // {min:5,message:"长度最少5个"}
              { pattern: /[0-9a-zA-Z\u4e00-\u9fa5_]{3,8}/, message: "允许字母数字中文,长度3-8" }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="type"
            label="分类类型"
          >
            <Select
              placeholder="请选中一个分类"
              allowClear
              onChange={typeChangeEvent}
            >
              <Option value="">请选中</Option>
              <Option value="一级分类">一级分类</Option>
              <Option value="二级分类">二级分类</Option>
            </Select>
          </Form.Item>

          {visible ? <Form.Item
            name="parentId"
            label="父级分类"
          >
            <Select
              placeholder="请选中一个分类"
              allowClear
            >
              {categoryList.map(item=>{
                return  <Option key={item._id} value={item._id}>{item.name}</Option>
              })}
            </Select>
          </Form.Item> : null}


          <Form.Item {...tailLayout}>
            <Space>
              <Button type="primary" htmlType="submit">
                Submit
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  )
}
